package net.fdukedom.epicurus.presentation.filters;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Helper class for filtering HTTP request.
 *
 * @author Dmitry Y. Kochelaev
 */
public abstract class AbstractHttpFilter implements Filter {

    /**
     * Filter configuration.
     */
    protected FilterConfig config;

    /**
     * Stores configuration in {@link #config} field.
     *
     * @param config filter configuration
     */
    public void init(FilterConfig config) {
        this.config = config;
    }

    /**
     * Calls {@link #doFilter(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,javax.servlet.FilterChain)}
     * method.
     *
     * @param servletRequest  servlet request.
     * @param servletResponse servlet response.
     * @param filterChain     filter chain.
     *
     * @throws IOException      if an I/O error occurred.
     */
    public final void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain
    ) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        doFilter(request, response, filterChain);
    }

    /**
     * Performs filtering.
     *
     * @param request     servlet request.
     * @param response    servlet response.
     * @param filterChain filter chain.
     *
     * @throws IOException      if an I/O error occurred.
     * @throws ServletException if an error occurred.
     */
    protected abstract void doFilter(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws IOException, ServletException;

    /**
     * Forgets configuration.
     */
    public void destroy() {
        this.config = null;
    }
}
